package generic.swing;

import java.util.LinkedList;
import java.util.List;
import javax.swing.AbstractListModel;

/**
 * TODO: This may be a change to create a decorator or facade or somthing...
 * @author Adam Scarr <scarr.adam@gmail.com>
 */
public class List2ListModelAdapter<Type> extends AbstractListModel {
    protected List<Type> list;

    public List2ListModelAdapter(List list) {
        this.list = list;
    }

    public synchronized void add(Type object) {
        list.add(object);

        fireContentsChanged(this, list.size() - 1, list.size() - 1);
    }

    public void remove(Type object) {
        int index = list.indexOf(object);
        if (index == -1 ) return;

        list.remove(object);
        fireIntervalRemoved(this, index, index);
    }

    public synchronized int getSize() {
        return list.size();
    }

    public List<Type> getList() {
        return list;
    }

    public synchronized Object getElementAt(int index) {
        if (list.size() > index) {
            return list.get(index);
        } else {
            return null;
        }
    }

    public synchronized void setList(List list) {
        int oldSize = this.list.size();
        this.list = new LinkedList();
        if (oldSize > 0) fireIntervalRemoved(this, 0, oldSize - 1);
        this.list = list;
        if (list.size() > 0) fireIntervalAdded(this, 0, list.size() - 1);
    }

}
